class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}
export default class SinglyLinkList {
    constructor() {
        this.head = null;
        this.length = 0;
    }

    append(data) {
        let newnode = new Node(data);
        if (this.length === 0) {
            this.head = newnode
        } else {
            let current = this.head;
            while (current.next) {
                current = current.next;
            }
            current.next = newnode;
        }
        this.length += 1;
    }

    insert(position, data) {
        if (position < 0 || position > this.length) return false
        let newnode = new Node(data);
        if (position === 0) {
            newnode.next = this.head;
            this.head = newnode
        } else {
            let index = 0;
            let current = this.head;
            let previous = null;
            while (index++ < position) {
                previous = current;
                current = current.next;
            }
            newnode = current;
            previous.next = newnode
        }
        this.length += 1
        return true
    }

    get(position) {
        if (position < 0 || position >= this.length) return null
        let current = this.head
        let index = 0
        while (index++ < position) {
            current = current.next
        }
        return current.data
    }

    indexOf(data) {
        let current = this.head
        let index = 0
        while (current) {
            if (current.data === data) {
                return index
            }
            current = current.next
            index += 1
        }
        return -1
    }

    updata(position, newdata) {
        if (position < 0 || position >= this.length) return false
        let current = this.head
        let index = 0
        while (index++ < position) {
            current = current.next
        }
        current.data = newdata
        return true
    }

    removeAt(position) {
        if (position < 0 || position >= this.length) return null
        let current = this.head
        if (position === 0) {
            this.head =this.head.next
        } else {
            let index = 0
            let previous = null
            while (index++ < position) {
                previous = current
                current = current.next
            }
            previous,next = current.next
        }
        this.length-=1
        return current

    }

    remove(data){
        return this.removeAt(this.indexOf(data))
    }

    isEmpty() {
        return this.length === 0;
    }

    size() {
        return this.length
    }
    toString() {
        let current = this.head;
        let result = '';
        while (current) {
            result += current.data + ' ';
            current = current.next;
        }
        return result;
    }
}